package com.fcy.teamwork.business.main.homepage

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.fcy.teamwork.base.BaseFragment
import com.fcy.teamwork.business.main.homepage.adapter.TaskMarketListAdapter
import com.fcy.teamwork.business.main.homepage.viewmodel.TaskMarketVM
import com.fcy.teamwork.databinding.HomepageTaskmarketBinding
import kotlinx.coroutines.launch

class TaskMarketFrag : BaseFragment<HomepageTaskmarketBinding>() {
    private val vm: TaskMarketVM by activityViewModels()

    private val adapter = TaskMarketListAdapter()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.apply {
            actionBar.tvTitle.text = "任务大厅"
            rvTaskMarket.adapter = adapter
            rvTaskMarket.layoutManager = LinearLayoutManager(this@TaskMarketFrag.context)
            rvTaskMarket.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    if (!recyclerView.canScrollVertically(1)) {
                        lifecycleScope.launch {
                            val nextPage = vm.insertNextPage()
                            adapter.insertData(nextPage)
                        }
                    }
                }
            })
            loadData()
        }
    }


    private fun loadData() {
        lifecycleScope.launchWhenCreated {
            repeatOnLifecycle(Lifecycle.State.RESUMED) {
                val jobs = vm.loadJobs()
                adapter.submitData(jobs)
            }
        }
    }

    override fun initViewBinding(
        inflater: LayoutInflater?,
        container: ViewGroup?
    ) = HomepageTaskmarketBinding.inflate(layoutInflater)

}